package iptux;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import baseclass.ImageListCellRenderer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;
import java.util.SortedMap;
import baseclass.JMIPV4AddressField;

/**
 * This dialog is the configuration UI, the data saves in mainDlg.configer.
 * @author cwll<cwll2009@126.com>
 *
 */
public class DialogConfig extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField textField_userName;
	private JTextField textField_groupName;
	private JMIPV4AddressField textField_2;
	private JMIPV4AddressField textField_3;
	JPanel panel_Replace;
	private JTextField textField_receivedFileSavePath;
	JList<Object[]> listConfigItem;
	Object[][] configModal ;
	JComboBox combo_msgEncoding;
	JCheckBox chckbx_enterKeySend;
	JCheckBox chckbx_saveChatHistory;
	JComboBox comboBox_iconSelf;
	JList<String> ipRanges;
	ButtonMonitor buttonMoniter;
	public Iptux mainDlg;

	private String activePane = "system";
	

	/**
	 * Create the dialog.
	 */
	public DialogConfig(Iptux frame,String tital,boolean modal) {
		//super(frame,tital,modal);
		this.mainDlg = frame;
		this.setTitle(tital);
		//this.setModal(modal);
		
		buttonMoniter = new ButtonMonitor();/* 创建一个监听对象 */
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		configModal = new Object[3][2];
		configModal[0][0] = new ImageIcon(Utils.readImageFromJar("/pixmaps/menu/list.png"));
		configModal[0][1] = "system";
		configModal[1][0] = new ImageIcon(Utils.readImageFromJar("/pixmaps/menu/list.png"));
		configModal[1][1] = "personal";
		configModal[2][0] = new ImageIcon(Utils.readImageFromJar("/pixmaps/menu/list.png"));
		configModal[2][1] = "network";
		setBounds(100, 100, 500, 300);
		getContentPane().setLayout(new BorderLayout());
		{
			JPanel panel = new JPanel();
			getContentPane().add(panel, BorderLayout.CENTER);
			panel.setLayout(new BorderLayout(0, 0));
			contentPanel.setPreferredSize(new Dimension(120, 10));
			panel.add(contentPanel, BorderLayout.WEST);
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			contentPanel.setLayout(new BorderLayout(0, 0));
			{
				listConfigItem = new JList<Object[]>();
				listConfigItem.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
				ListCellRenderer render = new ImageListCellRenderer();
				listConfigItem.setCellRenderer(render);
				listConfigItem.setListData(configModal);
				listConfigItem.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						int index;
						if (arg0.getSource() == listConfigItem){
							index = listConfigItem.locationToIndex(arg0.getPoint());
							String item = (String)(configModal[index][1]);
							if(item.equals("system")){
								showSystem();
							}
							if(item.equals("network")){
								showNetwork();
							}
							if(item.equals("personal")){
								showPersonal();
							}
						}
					}
				});
				contentPanel.add(listConfigItem);
			}
			{
				JPanel rightContent = new JPanel();
				panel.add(rightContent, BorderLayout.CENTER);
				
				rightContent.setLayout(new BorderLayout(0, 0));
				{
					panel_Replace = new JPanel();
					rightContent.add(panel_Replace, BorderLayout.CENTER);
				}

				{
					JPanel buttonPane = new JPanel();
					rightContent.add(buttonPane, BorderLayout.SOUTH);
					buttonPane.setLayout(new FlowLayout(FlowLayout.TRAILING));
					{
						JButton okButton = new JButton("OK");
						okButton.setActionCommand("OK");
						okButton.addActionListener(buttonMoniter);
						buttonPane.add(okButton);
						getRootPane().setDefaultButton(okButton);
					}
					{
						JButton cancelButton = new JButton("Cancel");
						cancelButton.setActionCommand("Cancel");
						cancelButton.addActionListener(buttonMoniter);
						buttonPane.add(cancelButton);
					}
				}
			}
		}
		showSystem();
	}
	
	/**
	 * show network config panel in content panel.
	 */
	public void showNetwork(){
		savePrevPaneData();
		activePane = "network";
		panel_Replace.removeAll();
		panel_Replace.setLayout(new BorderLayout(0, 0));

		JPanel panel_Network = new JPanel();
		panel_Replace.setLayout(new BorderLayout(0, 0));
		panel_Replace.add(panel_Network, BorderLayout.CENTER);

		panel_Network.setLayout(new BorderLayout(0, 0));
		{

			JPanel panel_2 = new JPanel();
			panel_2.setPreferredSize(new Dimension(10, 60));
			panel_Network.add(panel_2, BorderLayout.NORTH);
			panel_2.setLayout(new GridLayout(0, 1, 0, 0));
			{
				JLabel label = new JLabel();
				label.setText("Set broadcast ip address range");
				panel_2.add(label, BorderLayout.NORTH);

				JPanel panel_3 = new JPanel();
				FlowLayout flowLayout = (FlowLayout) panel_3.getLayout();
				flowLayout.setAlignment(FlowLayout.LEFT);
				panel_2.add(panel_3, BorderLayout.CENTER);
				panel_2.setPreferredSize(new Dimension(90, 90));
				{
					JLabel lblNewLabel_3 = new JLabel("from");
					lblNewLabel_3.setPreferredSize(new Dimension(40, 15));
					panel_3.add(lblNewLabel_3);
				}
				{
					textField_2 = new JMIPV4AddressField();
					//textField_2.setPreferredSize(new Dimension(210, 21));
					panel_3.add(textField_2);
					textField_2.setColumns(10);
					//textField_2.set
				}
				{
					JLabel lblNewLabel_4 = new JLabel("to");
					lblNewLabel_4.setPreferredSize(new Dimension(40, 15));
					panel_3.add(lblNewLabel_4);
				}
				{
					textField_3 = new JMIPV4AddressField();
					textField_3.setPreferredSize(new Dimension(90, 21));
					panel_3.add(textField_3);
					textField_3.setColumns(10);
				}
			}
			JPanel panel_3 = new JPanel();
			panel_Network.add(panel_3, BorderLayout.CENTER);
			panel_3.setLayout(new BorderLayout(0, 0));
			{
				JPanel panel_4 = new JPanel();
				panel_3.add(panel_4, BorderLayout.NORTH);
				{
					JButton addButthon = new JButton("add<<");
					panel_4.setLayout(new GridLayout(1, 2, 0, 0));
					panel_4.add(addButthon);
					JButton removeButthon = new JButton("delete>>");
					panel_4.add(removeButthon);
					removeButthon.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							deleteBroadcastIpRange();
						}
					});
					addButthon.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							addBroadcastIpRange();
						}
					});

				}
				JPanel panel_5 = new JPanel();
				panel_3.add(panel_5, BorderLayout.CENTER);
				panel_5.setLayout(new BorderLayout(0, 0));
				{
					ipRanges = new JList<String>();
					JScrollPane scrollPane = new JScrollPane(ipRanges);
					panel_5.add(scrollPane);
					ipRanges.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
					if((mainDlg.configer.broadcastRanges != null)&&(mainDlg.configer.broadcastRanges.length > 0)){
						ipRanges.setListData(mainDlg.configer.broadcastRanges);
					}
					ipRanges.addListSelectionListener(new ListSelectionListener(){
						@Override
						public void valueChanged(ListSelectionEvent arg0) {
							int index = arg0.getFirstIndex();	
							selectBroadcastRange(index);
						}
					});
				}
			}
		}
		this.setVisible(true);
			
	}
	
	/**
	 * Put the ip address pair to ip address input textfield,when clicked the 
	 * BroadcastRange list item.
	 * @param index
	 */
	public void selectBroadcastRange(int index){
		String ipPair = mainDlg.configer.broadcastRanges[index];
		String ipFrom = ipPair.split("-->")[0];
		String ipTo = ipPair.split("-->")[1];
		textField_2.setIpAddress(ipFrom.trim());
		textField_3.setIpAddress(ipTo.trim());
	}
	
	/**
	 * delete a item in BroadcastRange list.
	 */
	public void deleteBroadcastIpRange(){
		int index = ipRanges.getSelectedIndex();
		mainDlg.configer.broadcastRanges = Utils.deleteStringArrayItem(mainDlg.configer.broadcastRanges, index);
		ipRanges.setListData(mainDlg.configer.broadcastRanges);
	}
	
	/**
	 * add IP pairs in testfield to BroadcastRange list.
	 */
	public void addBroadcastIpRange(){
		//System.out.println(textField_2.getText());
		String ipFrom = textField_2.getText();
		String ipTo = textField_3.getText();
		String ipFromSubnet = ipFrom.substring(0, ipFrom.lastIndexOf(".")) ;
		String ipToSubnet = ipTo.substring(0, ipTo.lastIndexOf(".")) ;
		if(!ipFromSubnet.equals(ipToSubnet)){
			JOptionPane.showMessageDialog(this,
					" From ip address must in the same subnet with to ip address.",
				    "Invalid address pair",
				    JOptionPane.ERROR_MESSAGE);
			return;
		}
		int ipFromIP = textField_2.getIPValue();
		int ipToIP = textField_3.getIPValue();
		if(ipFromIP >= ipToIP){
			JOptionPane.showMessageDialog(this,
					" From ip address must smaller than to ip address.",
				    "Invalid address pair",
				    JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		if(mainDlg.configer.broadcastRanges == null){
			mainDlg.configer.broadcastRanges = new String[1];
		}else{
			String[] tmp = new String[mainDlg.configer.broadcastRanges.length];
			System.arraycopy(mainDlg.configer.broadcastRanges, 0, tmp, 0, mainDlg.configer.broadcastRanges.length);
			mainDlg.configer.broadcastRanges = new String[tmp.length+1];
			System.arraycopy(tmp, 0, mainDlg.configer.broadcastRanges, 0, tmp.length);
		}
		mainDlg.configer.broadcastRanges[mainDlg.configer.broadcastRanges.length-1] = textField_2.getText() + "-->" + textField_3.getText();
		ipRanges.setListData(mainDlg.configer.broadcastRanges);
	}
	
	/**
	 * show Personal config panel in content panel.
	 */
	public void showPersonal(){
		savePrevPaneData();
		activePane = "personal";
		panel_Replace.removeAll();
		panel_Replace.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_Perconal = new JPanel();
		panel_Replace.add(panel_Perconal,BorderLayout.CENTER);
		panel_Perconal.setLayout(new GridLayout(7, 1, 0, 0));
		{
			JPanel panel_2_1 = new JPanel();
			panel_Perconal.add(panel_2_1);
			panel_2_1.setLayout(null);
			{
				JLabel lblNewLabel = new JLabel("user name");
				lblNewLabel.setBounds(5, 8, 100, 15);
				panel_2_1.add(lblNewLabel);
			}
			{
				textField_userName = new JTextField();
				textField_userName.setBounds(103, 5, 166, 21);
				panel_2_1.add(textField_userName);
				textField_userName.setColumns(10);
				textField_userName.setText(mainDlg.configer.userName);
			}
		}
		{
			JPanel panel_3 = new JPanel();
			panel_Perconal.add(panel_3);
			panel_3.setLayout(null);
			{
				JLabel lblNewLabel_2 = new JLabel("group name");
				lblNewLabel_2.setBounds(5, 8, 100, 15);
				panel_3.add(lblNewLabel_2);
			}
			{
				textField_groupName = new JTextField();
				textField_groupName.setBounds(103, 5, 167, 21);
				panel_3.add(textField_groupName);
				textField_groupName.setColumns(10);
				textField_groupName.setText(mainDlg.configer.groupName);
			}
		}
		{
			JPanel panel_3 = new JPanel();
			panel_Perconal.add(panel_3);
			panel_3.setLayout(null);
			{
				JLabel lblNewLabel_1 = new JLabel("icon");
				lblNewLabel_1.setBounds(5, 8, 54, 15);
				panel_3.add(lblNewLabel_1);
			}
			{
				comboBox_iconSelf = new JComboBox();
				comboBox_iconSelf.setBounds(84, 5, 73, 31);
				panel_3.add(comboBox_iconSelf);
				//read icons from jar file.
				ArrayList<String> iconPath = Utils.ListJarFile("pixmaps/icon");
				for(String imageFile:iconPath){
					byte[] buffer = Utils.readImageFromJar(imageFile);
					ImageIcon image = new ImageIcon(buffer);
					image.setDescription(imageFile);
					comboBox_iconSelf.addItem(image);
					comboBox_iconSelf.setToolTipText("This feature is not supported now!");
					if(imageFile.equals(mainDlg.configer.icon)){
						comboBox_iconSelf.setSelectedItem(image);
					}
					//System.out.println(image.toString());
				}
				
			}
		}
		
		this.setVisible(true);
	}
	
	/**
	 * show System config panel in content panel.
	 */
	public void showSystem(){
		savePrevPaneData();
		activePane = "system";
		panel_Replace.removeAll();
		panel_Replace.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_System = new JPanel();
		panel_Replace.add(panel_System,BorderLayout.CENTER);
		panel_System.setLayout(new GridLayout(6, 1, 0, 0));
		{
			JPanel panel_1 = new JPanel();
			FlowLayout flowLayout = (FlowLayout) panel_1.getLayout();
			flowLayout.setAlignment(FlowLayout.LEFT);
			panel_System.add(panel_1);
			{
				JLabel lblNewLabel_6 = new JLabel("<html>default message sending<br>language encode</html>");
				panel_1.add(lblNewLabel_6);
			}
			{

				combo_msgEncoding = new JComboBox();
				panel_1.add(combo_msgEncoding);
				SortedMap<String,Charset> charsets =  Charset.availableCharsets();
				String[] charsetNames = new String[charsets.size()];
				int index = 0;
				String currentCharset = null;
				for(Map.Entry entry: charsets.entrySet()){
					String charsetName = (String)(entry.getKey( ));
					charsetNames[index] = charsetName;
					index =  index + 1;
					if(mainDlg.configer.msgEncoding.equals(charsetName)){
						currentCharset = charsetName;
					}
				}
				combo_msgEncoding.setModel(new DefaultComboBoxModel(charsetNames));
				combo_msgEncoding.setSelectedItem(currentCharset);
			}
		}
		{
			chckbx_enterKeySend = new JCheckBox("\"Enter\" and \"CTRL\" key combine to send message");
			panel_System.add(chckbx_enterKeySend);
			chckbx_enterKeySend.setSelected(mainDlg.configer.enterKeySend);
			chckbx_enterKeySend.addChangeListener(new ChangeListener() {
				@Override
				public void stateChanged(ChangeEvent e) {
					mainDlg.configer.enterKeySend = chckbx_enterKeySend.isSelected();
				}
			});

		}
		{
			chckbx_saveChatHistory = new JCheckBox("save chat history");
			panel_System.add(chckbx_saveChatHistory);
			chckbx_saveChatHistory.setSelected(mainDlg.configer.saveChatHistory);
			chckbx_saveChatHistory.addChangeListener(new ChangeListener(){
				@Override
				public void stateChanged(ChangeEvent e) {
					mainDlg.configer.saveChatHistory = chckbx_saveChatHistory.isSelected();
				}
			});
		}
		{
			JPanel panel_1 = new JPanel();
			panel_System.add(panel_1);
			panel_1.setLayout(null);
			{
				JLabel lblDefalutSaveFiles = new JLabel("defalut save files to");
				panel_1.add(lblDefalutSaveFiles);
				lblDefalutSaveFiles.setBounds(0, 0, 145, 25);
			}
			{
				textField_receivedFileSavePath = new JTextField();
				panel_1.add(textField_receivedFileSavePath);
				textField_receivedFileSavePath.setColumns(10);
				textField_receivedFileSavePath.setText(mainDlg.configer.fileSavePath);
				textField_receivedFileSavePath.setBounds(145, 0, 200, 25);
			}
			{
				JButton button = new JButton("...");
				panel_1.add(button);
				button.setBounds(345, 0, 20, 25);
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						String saveFolder = chooseFileSaveDir();
					}
				});
			}
		}
		this.setVisible(true);
	}
	
	/**
	 * show a folder choose dialog.
	 * @return
	 */
	public String chooseFileSaveDir(){
		JFileChooser fileDialog = new JFileChooser();
		fileDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		fileDialog.setDialogTitle("Select a folder to save received files to");
		fileDialog.setMultiSelectionEnabled(false);
		int flag = fileDialog.showSaveDialog(this);
		File file = null;
		if(flag == JFileChooser.APPROVE_OPTION){   
			file = fileDialog.getSelectedFile();    
         }
		if(file == null){
			return null;
		}
		textField_receivedFileSavePath.setText(file.getPath());
		return file.getPath();
	}
	
	/**
	 * when the active panel changed, save the config data.
	 */
	public void savePrevPaneData(){
		if(panel_Replace.getComponentCount() < 1){
			return;
		}
		if(this.activePane.equals("system")){
			mainDlg.configer.msgEncoding = combo_msgEncoding.getSelectedItem().toString();
			mainDlg.configer.enterKeySend = chckbx_enterKeySend.isSelected();
			mainDlg.configer.saveChatHistory = chckbx_saveChatHistory.isSelected();
			mainDlg.configer.fileSavePath = textField_receivedFileSavePath.getText();
		}
		if(this.activePane.equals("personal")){
			mainDlg.configer.userName = textField_userName.getText();
			mainDlg.configer.groupName = textField_groupName.getText();
			ImageIcon image = (ImageIcon)(this.comboBox_iconSelf.getSelectedItem());
			mainDlg.configer.icon = image.getDescription();
		}
		if(this.activePane.equals("network")){

		}
	}
	
	/**
	 * save config settings.
	 */
	public void saveSettings(){
		savePrevPaneData();
		this.mainDlg.configer.save();
	}
	
	/**
	 * Close this dialog and release dialog resource.
	 */
	public void exitConfig(){
		this.setVisible(false);
		this.dispose();
	}
	
	/*
	 * 自定义Monitor(监听)类实现事件监听接口ActionListener 一个类要想成为监听类，那么必须实现ActionListener接口
	 */
	class ButtonMonitor implements ActionListener {
	    /* 重写ActionListener接口里面的actionPerformed(ActionEvent e)方法 */
	    public void actionPerformed(ActionEvent e) {
	    	String actionCommand = e.getActionCommand();
	    	if(actionCommand.equals("OK")){
	    		saveSettings();
	    		exitConfig();
	    	}else if(actionCommand.equals("Cancel")){
	    		exitConfig();
	    	}
	    }
	}
	
}

